package com.jrx.anytxn.param.job.bactchlimitadjust.step;

import com.jrx.anytxn.common.uitl.JsonUtils;
import com.jrx.anytxn.common.uitl.SeqUtils;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.entity.BtLimitAdjustInfo;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 批量调额processor
 *
 * @author : zhenghaopu
 * 2020/1/6
 */
@Service
public class BatchLimitAdjustStep2Processor implements ItemProcessor<BtLimitAdjustInfo,BtLimitAdjustInfo> {

    private final Logger logger = LoggerFactory.getLogger(BatchLimitAdjustStep2Processor.class);

    @Autowired
    private ISegmentService segmentService;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public BtLimitAdjustInfo process(BtLimitAdjustInfo btLimitAdjustInfo) throws Exception {

        BtLimitAdjustInfo updateBtLimitAdjustInfo = buildUpdateBtLimitAdjustInfo(btLimitAdjustInfo);
        try {
            //发送调额消息
            SendResult sendResult = rocketMQTemplate.syncSend(Constant.MQ_BATCH_LIMIT_ADJUST_TOPIC,
                    JsonUtils.obj2jsonIgnoreNull(btLimitAdjustInfo));
            //MQ发送是否成功
            if(SendStatus.SEND_OK  != sendResult.getSendStatus()){
                updateBtLimitAdjustInfo.setMqStatus(Constant.MQ_SATTUS_2);
            }
        }catch (Exception e){
            logger.error(ErrorMsgConstant.MQ_SEND_ERROR,e);
            updateBtLimitAdjustInfo.setMqStatus(Constant.MQ_SATTUS_2);
        }
        return  updateBtLimitAdjustInfo;
    }

    /**
     * 构建要修改的调额信息
     *
     * @param btLimitAdjustInfo 批量调额信息
     *
     */
    private BtLimitAdjustInfo buildUpdateBtLimitAdjustInfo(BtLimitAdjustInfo btLimitAdjustInfo) {
        BtLimitAdjustInfo updateBtLimitAdjustInfo = new BtLimitAdjustInfo();
        updateBtLimitAdjustInfo.setId(btLimitAdjustInfo.getId());
        updateBtLimitAdjustInfo.setMqStatus(Constant.MQ_SATTUS_1);
        updateBtLimitAdjustInfo.setUpdateBy(btLimitAdjustInfo.getUpdateBy());
        return updateBtLimitAdjustInfo;
    }
}
